package practice;

import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;

import com.google.api.server.spi.response.NotFoundException;

public class APIResponse implements Serializable {

	private static final long serialVersionUID = 1L;

	public enum Status {
		SUCCESS, ERROR_LOGIN_REQUIRED, ERROR_INVALID_USER, ERROR_INSUFFICIENT_PERMISSION, ERROR_RESOURCE_DOES_NOT_EXIST, ERROR_RESOURCE_ALREADY_EXISTS, ERROR_RESOURCE_NOT_FULLY_SPECIFIED, ERROR_RESOURCE_INCORRECTLY_SPECIFIED, ERROR_PRECONDITION_FAILED, ERROR_UNHANDLED_EXCEPTION, ERROR_NOT_IMPLEMENTED, ERROR_INTERNAL, ERROR_OPERATION_NOT_ALLOWED, PAYPAL_ERROR
	}

	public Status statusCode;
	public String userFriendlyMessage;
	public Object object;

	public APIResponse(Status statusCode, Object object) {
		this.statusCode = statusCode;
		this.object = object;
	}

	public APIResponse() {
	}

	public APIResponse(Exception ex) {

		if (ex instanceof APIException) {
			APIException apiException = (APIException) ex;
			statusCode = apiException.statusCode;
			userFriendlyMessage = apiException.userFriendlyMessage;
		} else if (ex instanceof NotFoundException) {
			statusCode = Status.ERROR_RESOURCE_DOES_NOT_EXIST;
			userFriendlyMessage = "Objectify not found exception";
		} else {
			statusCode = Status.ERROR_UNHANDLED_EXCEPTION;
			userFriendlyMessage = "Unhandled exception. Please inform the development team.";
		}

		object = "Stack trace: \n" + stackTraceToString(ex);
	}

	private String stackTraceToString(Throwable e) {
		StringWriter sw = new StringWriter();
		e.printStackTrace(new PrintWriter(sw));

		return sw.toString();
	}
}
